package com.sali.controller;

import com.google.common.util.concurrent.RateLimiter;
import com.sali.pojo.Stock;
import com.sali.service.IStockService;
import com.sali.utils.limiter.CustomTokenAlgorithm;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @description:
 * @author: zhang hang
 * @date: 2022/7/18 16:31.
 * @version: 1.0
 */
@RestController
public class StockController {

    @Resource
    IStockService stockService;


    /**
     * description: 创建令牌桶实例
     **/
    private RateLimiter rateLimiter = RateLimiter.create(2);

    /**
     * description: 创建令牌桶实例(手写)
     **/
    static CustomTokenAlgorithm limiter = new CustomTokenAlgorithm(8, 1000, 2);

    static {
        // 初始化令牌桶
        limiter.init();
        // 令牌桶添加令牌
        Object lock = new Object();
        limiter.start(lock);
        synchronized (lock) {
            try {
                lock.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @GetMapping("/stock/{id}")
    public Stock findById(@PathVariable Long id) {

        // 令牌桶限流算法
//        ILimiterAlgorithm limiterAlgorithm = new TokenAlgorithm();
//        boolean flag = limiterAlgorithm.algorithmDetail(rateLimiter);

        // 手写令牌桶限流算法
        boolean flag = limiter.tryAcquire();

        Stock stock = new Stock();
        if (flag) {
            System.out.println("执行查询了。。。。。。。。");
            stock = stockService.getById(id);
        } else {
            System.out.println("当前请求被限流，直接抛弃");
            stock.setName("当前请求被限流，直接抛弃");
        }
        return stock;
    }


}
